package com.lantosec.hmrp.modules.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.kit.Result;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.core.util.DateUtils;
import com.lantosec.hmrp.core.util.UUIDUtils;
import com.lantosec.hmrp.modules.archives.entity.UserInfo;
import com.lantosec.hmrp.modules.archives.service.IUserInfoService;
import com.lantosec.hmrp.modules.form.mapper.FormColumnsMapper;
import com.lantosec.hmrp.modules.system.entity.SysDept;
import com.lantosec.hmrp.modules.system.entity.SysDeptUser;
import com.lantosec.hmrp.modules.system.entity.SysUser;
import com.lantosec.hmrp.modules.system.mapper.SysUserMapper;
import com.lantosec.hmrp.modules.system.service.ISysDeptService;
import com.lantosec.hmrp.modules.system.service.ISysUserService;
import com.lantosec.hmrp.modules.system.vo.SysUserVO;
import com.lantosec.hmrp.modules.system.vo.UserQueryVO;
import com.lantosec.hmrp.modules.workflow.enumeration.TaskOperatorTypeEnum;
import com.lantosec.hmrp.modules.workflow.vo.TaskOperatorVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-02-07
 */
@Service
@Primary
@Log4j2
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    ISysDeptService deptService;
    @Autowired
    FormColumnsMapper formColumnsMapper;

    @Autowired
    private IUserInfoService iUserInfoService;

    @Override
    public SysUser getByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<SysUser>().eq(SysUser.ColName.username.toString(),username));
    }

    @Override
    public Integer resetPassword(String userId) {
        return baseMapper.resetPassword(userId);
    }

    @Override
    public Integer queryUsernameAndPhoneUniqueness(String username, String phone) {
        Integer count = baseMapper.selectCount(new QueryWrapper<SysUser>().select()
                .eq(StringUtils.isNotEmpty(username), "username", username)
                .or()
                .eq(StringUtils.isNotEmpty(phone), "phone", phone));
        return count;
    }


    @Override
    public Integer updateUsernameAndPhone(String userName, String phone) {
        Integer result = 0;
        result = baseMapper.selectCount(new QueryWrapper<SysUser>().select()
                .eq(StringUtils.isNotEmpty(userName), "username", userName)
                .eq(StringUtils.isNotEmpty(phone), "phone", phone));
        if(result == 1){
            return 0;
        }else{
            result = baseMapper.selectCount(new QueryWrapper<SysUser>().select()
                    .eq(StringUtils.isNotEmpty(phone), "phone", phone));
            return result;
        }
    }

    @Override
    public Page<SysUserVO> queryUserList(PageVO<SysUser> page, String name,String username ,String deptId, String state) {
        /*Page<SysUser> p = baseMapper.selectPage(page,new QueryWrapper<SysUser>()
                .like(StringUtils.isNotEmpty(name),"name",name)
                .eq(StringUtils.isNotEmpty(deptId),"dept_id",deptId)
                .eq(StringUtils.isNotEmpty(state),"state",state));*/
        List list = baseMapper.queryUserList(page,name,username,deptId,state);
        return page.setRecords(list);

    }

    @Override
    public List queryAllRole() {
        return baseMapper.queryAllRole();
    }

    @Override
    public List queryRoleByUserId(String userId) {
        return baseMapper.queryRoleByUserId(userId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveUserRoleInfo(String userId, String roleIds) {
        //查询用户的角色信息
        List param = baseMapper.queryRoleByUserId(userId);
        if(param.size() != 0){
            //给用户新增角色先删除其原有角色，再新增角色
            baseMapper.deleteUserRole(userId);
        }
            List<String> list = Arrays.asList(roleIds.split(","));
            list.forEach(it-> baseMapper.saveUserRoleInfo(userId,it));
    }

    /**
     * 部门人员查询
     * @param page
     * @param deptId
     * @return
     */
    @Override
    public List<SysUserVO>  queryDeptUserList(PageVO<SysUserVO> page, String deptId, String positionId, String name) {
        List<SysUserVO> list = baseMapper.queryDeptUserList(page, deptId, positionId, name);
        page.setRecords(list);
        return list;
    }

    @Override
    public void updateUserDeptInfo(SysDeptUser user,List<SysDeptUser> param) {
        baseMapper.deleteUserDeptInfo(user.getUserId());
        saveUserDeptInfo(user,param);
    }

    @Override
    public void saveUserDeptInfo(SysDeptUser user,List<SysDeptUser> param) {
        String s = JSON.toJSONString(param);
        List<SysDeptUser> sysDeptUsers = JSON.parseArray(s, SysDeptUser.class);
        String mainDept = user.getMainDept();
        sysDeptUsers.forEach(it->{
            user.setDeptId(it.getDeptId());
            user.setPositionId(it.getPositionId());
            if(mainDept.equals(it.getDeptId())){
                user.setMainDept("1");
            }else{
                user.setMainDept("0");
            }
            baseMapper.saveUserDeptInfo(user);
        });
    }

    @Override
    public List<SysUser> queryUserByDeptId(String deptId) {
        List param = new ArrayList();
        List<SysUser> list = baseMapper.queryUserByDeptId(deptId);
        list.forEach(it->{
            SysUser user = new SysUser();
            String userId = it.getUserId();
            String name = it.getName();
            user.setUserId(userId);
            user.setName(name);
            param.add(user);
        });
        return param;
    }

    @Override
    public List<SysUser> getAll() {
        List<SysUser> sysUserList = this.list();
        sysUserList.forEach(parm->{
            List<String> deptIdList = baseMapper.getDeptIdByUserId(parm.getUserId());
            if(null != deptIdList && deptIdList.size() >0){
                for(int i = 0;i<deptIdList.size();i++){
                    SysDept sysDept = deptService.getById(deptIdList.get(i));
                    parm.setName(parm.getName()+"-"+sysDept.getDeptName());
                }
            }
        });
        return sysUserList;
    }

    @Override
    public List<SysUser> queryUser(String deptId, String positionId) {
        return baseMapper.queryUser(deptId, positionId);
    }

    @Override
    public List<String> queryUserIdList(UserQueryVO queryVO) {
        List<String> userIdList = new ArrayList<>();
        if (Objects.isNull(queryVO)) {
            return userIdList;
        }
        if (StringUtils.isNotBlank(queryVO.getUserId())) {
            userIdList.add(queryVO.getUserId());
        } else {
            List<SysUser> list = baseMapper.queryUser(queryVO.getDeptId(), queryVO.getPositionId());
            if (CollectionUtils.isNotEmpty(list)) {
                userIdList = list.stream().map(SysUser::getUserId).collect(Collectors.toList());
            }
        }
        return userIdList;
    }

    @Override
    public List<String> getOperatorUserIdList(String operator, JSONObject dataJson, String userId){
        List<String> optUserList = new ArrayList<>();
        if (StringUtils.isBlank(operator)) {
            return optUserList;
        }
        TaskOperatorVO taskOperatorVO = JSON.parseObject(operator,TaskOperatorVO.class);
        if(Objects.isNull(taskOperatorVO)){
            return optUserList;
        }
        TaskOperatorTypeEnum optTypeEnum = TaskOperatorTypeEnum.getByType(taskOperatorVO.getOptType());
        String data = taskOperatorVO.getData();
        switch (optTypeEnum) {
            case SQL:
                // 替换文本的字段，默认取当前对象的参数，用${field}
                String parameter = com.lantosec.hmrp.core.util.StringUtils.processTemplate(data, dataJson);
                // 这条SQL只能查询UserId
                List<String> sqlList = formColumnsMapper.executeSql(parameter);
                if (CollectionUtils.isNotEmpty(sqlList)) {
                    optUserList.addAll(sqlList);
                }
                break;
            case MANAGER:
                List<UserQueryVO> deptList = JSONObject.parseArray(data, UserQueryVO.class);
                if (CollectionUtils.isNotEmpty(deptList)) {
                    List<String> chargeDeptIdList = deptList.stream().map(UserQueryVO::getDeptId).collect(Collectors.toList());
                    // 根据部门ID查询部门管理者（一个部门一个人）
                    List<String> chargeIdList = baseMapper.queryChargeUserIdByDeptIds(chargeDeptIdList);
                    optUserList.addAll(chargeIdList);
                }
                break;
            case SUPERIOR:
                // 根据当前任务的用户Id查询上级管理岗
                List<String> parentIdList = baseMapper.queryParentUserIdByUserId(userId);
                optUserList.addAll(parentIdList);
                break;
            case DEPARTMENT:
                List<UserQueryVO> managerList = JSONObject.parseArray(data, UserQueryVO.class);
                if (CollectionUtils.isNotEmpty((managerList))) {
                    List<String> managerDeptIdList = managerList.stream().map(UserQueryVO::getDeptId).collect(Collectors.toList());
                    // 根据部门ID查询部门管理岗（一个部门可能有多个）
                    List<String> managerIdList = baseMapper.queryManagerUserIdByDeptIds(managerDeptIdList);
                    optUserList.addAll(managerIdList);
                }
                break;
            case ROLE:
                if(StringUtils.isNotEmpty(data)) {
                    // 角色Id数组
                    List<String> roleIdList = JSONObject.parseArray(data, String.class);
                    if (CollectionUtils.isNotEmpty(roleIdList)) {
                        // 根据角色ID集合查询用户
                        List<String> roleUserIdList = baseMapper.queryUserIdByRoleIds(roleIdList);
                        optUserList.addAll(roleUserIdList);
                    }
                }
                break;
            default:
                List<UserQueryVO> userList = JSONObject.parseArray(data, UserQueryVO.class);
                if (CollectionUtils.isNotEmpty(userList)) {
                    for (UserQueryVO item : userList) {
                        // 根据参数查询部门或者人员
                        optUserList.addAll(this.queryUserIdList(item));
                    }
                }
                break;
        }

        if (CollectionUtils.isNotEmpty(optUserList)) {
            // 去重
            optUserList = optUserList.stream().distinct().collect(Collectors.toList());
        }

        return optUserList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertOrUpdateUserInfo(SysUserVO vo) {
        SysUser entity = vo.convertToEntity();
        entity.setState(0);
        this.save(entity);           //保存用户信息至用户表  sys_user
        SysDeptUser user = new SysDeptUser();
        user.setMainDept(vo.getMainDept());
        user.setUserId(entity.getUserId());
        saveUserDeptInfo(user,vo.getParam());
        //this.saveUserDeptInfo(user,vo.getParam());         //保存用户部门及岗位信息 sys_dept_user
        //新增用户信息表
        UserInfo userInfo = new UserInfo();
        userInfo.setUserInfoId(UUIDUtils.get());
        userInfo.setUserId(entity.getUserId());
        userInfo.setEmployeeId(entity.getUsername());
        userInfo.setName(entity.getName());
        //获取当前用户id和名称
        userInfo.setCreateId(TokenUtil.getUserId());
        userInfo.setCreateUser(TokenUtil.getName());
        userInfo.setCreateTime(DateUtils.nowDate());
        iUserInfoService.save(userInfo);
        return entity.getUserId();
    }

    @Override
    public SysDeptUser getDeptInfo(String userId) {
        return baseMapper.getDeptInfo(userId);
    }

    @Override
    public String getPermissionList(String roleId) {
        return baseMapper.getPermissionList(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(SysUserVO vo) {
        SysUser entity = vo.convertToEntity();
        String userId = entity.getUserId();
        this.updateById(entity);          //保存用户信息至用户表  sys_user
        SysDeptUser user = new SysDeptUser();
        user.setUserId(userId);
        user.setMainDept(vo.getMainDept());
        this.updateUserDeptInfo(user,vo.getParam());         //保存用户部门及岗位信息 sys_dept_user
        //修改用户信息表user_info
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setEmployeeId(entity.getUsername());
        userInfo.setName(entity.getName());
        userInfo.setPhone(entity.getPhone());
        iUserInfoService.update(userInfo,new QueryWrapper<UserInfo>().eq(UserInfo.ColName.user_id.toString(),userId));
    }

    @Override
    public List<SysDeptUser> getDeptAndPositionList(String userId) {
        return baseMapper.getDeptAndPositionList(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updatePassword(SysUserVO vo) {
        String oldPassword = vo.getOldPassword();
        String newPassword = vo.getNewPassword();
        //获取当前用户ID
        String userId = TokenUtil.getUserId();
        //查询旧密码是否是该用户的密码
        SysUser sysUser = baseMapper.getUserPassword(userId,oldPassword);
        if(Objects.isNull(sysUser)){
            return Result.ok("旧密码错误！",false);
        }else {
            //修改用户密码
            baseMapper.updateUserPassword(userId,newPassword);
            return Result.ok("密码修改成功！",true);
        }
    }
}
